package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"novel-world/cache"
	"novel-world/models"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	author := c.PostForm("author")
	types := c.PostForm("types")
	status := c.PostForm("status")
	content := c.PostForm("content")

	data := models.Novel{

		Title:   title,
		Author:  author,
		Types:   types,
		Status:  status,
		Content: content,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	reds_key := "reds_add" + strconv.Itoa(int(data.ID))
	var nov models.Novel
	models.DB.Where("id=?", data.ID).First(&nov)
	jsonData, _ := json.Marshal(nov)
	cache.Rdb.Set(cache.Ctx, reds_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "2"))
	offset := (page - 1) * pageSize

	var arr []models.Novel
	red_key := "reds_list" + strconv.Itoa(page)
	redData, _ := cache.Rdb.Get(cache.Ctx, red_key).Result()
	if redData == "" {
		models.DB.Offset(offset).Limit(pageSize).Find(&arr)
		jsondata, _ := json.Marshal(arr)
		cache.Rdb.Set(cache.Ctx, red_key, jsondata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redData), &arr)
	}
	var total int64
	models.DB.Model(&models.Novel{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"total": total,
		"list":  arr,
	})
}
func Detail(c *gin.Context) {
	id := c.Query("id")

	var arr models.Novel
	red_key := "reds_detail" + id
	redData, _ := cache.Rdb.Get(cache.Ctx, red_key).Result()
	if redData == "" {
		models.DB.Where("id=?", id).Find(&arr)
		jsondata, _ := json.Marshal(arr)
		cache.Rdb.Set(cache.Ctx, red_key, jsondata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redData), &arr)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": arr,
	})
}
func Del(c *gin.Context) {
	id := c.Query("id")
	var arr models.Novel
	trach_key := "trac_del" + id
	models.DB.Where("id=?", id).Delete(&arr)
	cache.Rdb.Del(cache.Ctx, trach_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
}
